package com.lx.tomcat.server;

import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;

public class TaskQueue<Runnable> extends LinkedBlockingQueue<Runnable> {
    // 线程池
    private ThreadPoolExecutor executor;

    public TaskQueue(int capacity) {
        super(capacity);
    }

    public void setExecutor(ThreadPoolExecutor executor) {
        this.executor = executor;
    }

    @Override
    public boolean offer(Runnable runnable) {
        if (executor == null){
            return super.offer(runnable);
        }
        // Tomcat 核心逻辑的模拟实现
        int poolSize = executor.getPoolSize();
        long taskCount = executor.getTaskCount(); // 注意：这是一个近似值，并非精确的 submittedCount
        int maxPoolSize = executor.getMaximumPoolSize();
        // 线程池正常逻辑: 未到达核心线程启动核心线程, 已到达核心线程,加入队列 队列满啦开启非核心线程直到最大线程数
        if (poolSize == maxPoolSize){ // 线程已满
            return super.offer(runnable);
        }
        if (taskCount<=poolSize){ //已提交任务数<=活跃线程 有活跃线程,不应该创建新线程
            return super.offer(runnable);
        }
        if (poolSize<maxPoolSize){ //没有空闲线程 创建新线程
            return false;
        }
        return super.offer(runnable);
    }
}
